import os

from src.api.https import SUCCESS, FAIL, fail_api, success_api, table_api
from flask import Blueprint, request, session

from src.utils.check_require import login_required
from src.utils.picture_tool import PictureTool
from src.utils.res_tool import ResTool

from src.init.init_path import PATH, AVATAR_PATH, BASE_PATH

from src.utils.user_tool import UserTool
from flask import current_app

# 创建蓝图
res_api = Blueprint("resource", __name__, url_prefix="/api/res")

res_tool = ResTool()
ptool = PictureTool()
ALLOW_TYPE = ["jpg", "png", "gif", "svg", "jpeg"]


@res_api.post("/avatar")
@login_required
def update_avatar():
    # 更新用户头像
    file = request.files.getlist("file")
    uid = str(session["uid"])

    # 首先查看用户头像是否存在，存在则删除原图片，上传新头像进行更新，否则仅上传新头像
    filetype = file[0].filename.split(".")[-1]
    filetype = filetype.lower()
    if filetype not in ALLOW_TYPE:
        return fail_api(msg="不允许的文件类型")

    for filetype_maybe in ALLOW_TYPE:
        url = os.path.join(current_app.static_folder + AVATAR_PATH, uid + "." + filetype_maybe)
        if os.path.exists(url) and os.path.isfile(url):
            try:
                os.remove(url)  # 删除文件
                print(f"文件 {url} 已成功删除")
            except Exception as e:
                print(f"删除文件时出错: {e}")

    url = os.path.join(current_app.static_folder + AVATAR_PATH, uid + "." + filetype)
    purl = os.path.join(BASE_PATH + AVATAR_PATH, uid + "." + filetype)
    file[0].save(url)
    data = {"avatar": purl}
    utool = UserTool()
    utool.update(data, uid)
    data = {"avatar": "http://" + request.host + "/" + purl}
    return table_api(data=data)


@res_api.post("/upload")
@login_required
def up_picture():
    # 编辑过程中上传图片
    global ptool
    aid = int(request.form.get("aid"))
    file = request.files.get("file")
    msg = ptool.init(aid, file)
    if msg["pid"] == 0:
        return fail_api(msg["err"])
    msg["purl"] = "http://" + request.host + "/" + msg["purl"]
    return success_api(data=msg)
